package tr.edu.ozyegin.ccrg.raid.config;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ConfigManager {
	private Document dom = null;
	private ArrayList<ConfigElement> confList = new ArrayList<ConfigElement>();
	private static ConfigManager _instance = null;
	public static ConfigManager getInstance(String file){
		if(_instance == null)_instance = new ConfigManager(file);
		return _instance;
	}
	public static ConfigManager getInstance(){
		return _instance;
	}
	private ConfigManager(String file){
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			//parse using builder to get DOM representation of the XML file
			dom = db.parse(file);
			this.parseDocument();

		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
	private void parseDocument(){
		Element docEle = dom.getDocumentElement();

		NodeList nl = docEle.getElementsByTagName("property");
		if(nl != null && nl.getLength() > 0) {
			for(int i = 0 ; i < nl.getLength();i++) {

				Element el = (Element)nl.item(i);
				this.confList.add(this.getElement(el));
			}
		}
	}
	public ConfigElement searchByKey(String key){
		ConfigElement tmp = null;
		for(int i = 0; i < this.confList.size(); i++){
			tmp = (ConfigElement)this.confList.get(i);
			if(tmp.getKey().compareToIgnoreCase(key) == 0)return tmp;
		}
		return null;
	}
	public ConfigElement searchByValue(String value){
		ConfigElement tmp = null;
		for(int i = 0;i < this.confList.size(); i++){
			tmp = this.confList.get(i);
			if(tmp.getValue().compareToIgnoreCase(value) == 0)return tmp;
		}
		return null;
	}
	private String getTextValue(Element element, String tagName) {
		String textVal = null;
		NodeList nl = element.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}
	private ConfigElement getElement(Element element){
		String key = getTextValue(element,"key");
		String value = getTextValue(element,"value");
		return new ConfigElement(key, value);
	}
}
